<template>
	<view class="share-card">
		<canvas :canvas-id="canvasId" class="share-canvas"
			:style="{width: width + 'px', height: height + 'px'}"></canvas>
	</view>
</template>

<script>
	export default {
		name: 'ShareCard',
		props: {
			avatar: {
				type: String,
				required: true
			},
			nickname: {
				type: String,
				required: true
			},
			qrcode: {
				type: String,
				required: true
			},
			tip: {
				type: String,
				default: "打开微信扫一扫识别二维码"
			},
			values: {
				type: Object,
				required: true
			},
			width: {
				type: Number,
				default: 375
			},
			height: {
				type: Number,
				default: 400
			}
		},
		data() {
			return {
				ctx: null,
				pixelRatio: 1,
				canvasId: "canvas-" + new Date().getTime()
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			async init() {
				this.ctx = uni.createCanvasContext(this.canvasId, this)
				this.pixelRatio = uni.getSystemInfoSync().pixelRatio

				try {
					// Load all images first
					const [bgImage, avatarImage, qrcodeImage] = await Promise.all([
						this.loadImage("https://file.dgyxy.com/resource/bgDefault.png"),
						this.loadImage(this.avatar),
						this.loadImage(this.qrcode)
					])
					// Draw everything once images are loaded
					this.ctx.drawImage(bgImage, 0, 0, this.width, this.height)
					this.drawCard()

					// Draw avatar with loaded image
					const avatarSize = 65
					const avatarX = 35
					const avatarY = 0
					this.ctx.save()
					this.ctx.beginPath()
					this.ctx.arc(avatarX + avatarSize / 2, avatarY + avatarSize / 2, avatarSize / 2, 0, 2 * Math.PI)
					this.ctx.clip()
					this.ctx.drawImage(avatarImage, avatarX, avatarY, avatarSize, avatarSize)
					this.ctx.restore()

					this.drawNickname()
					this.drawValues()

					// Draw QR code with loaded image
					const qrSize = 180
					const qrX = (this.width - qrSize) / 2
					const qrY = 130
					this.ctx.drawImage(qrcodeImage, qrX, qrY, qrSize, qrSize)

					this.drawTips()

					// Execute final draw
					this.ctx.draw(false, () => {
						this.$emit("over", this.canvasId)
					})
				} catch (error) {
					console.error('Error loading images:', error)
				}
			},

			loadImage(src) {
				return new Promise((resolve, reject) => {
					resolve(src)
					/* uni.request({
						url: src,
						method: 'GET',
						responseType: 'arraybuffer',
						success: res => {
							let base64 = uni.arrayBufferToBase64(res.data)
							base64 && (base64 = 'data:image/jpeg;base64,' + base64)
							resolve(base64)
						},
						fail: () => resolve('')
					}) */
					/* uni.downloadFile({
						url: src,
						success: (res) => {
							if (res.statusCode === 200) {
								resolve(res)
							} else {
								reject(new Error(`Failed to load image: ${src}`))
							}
						},
						fail: (err) => {
							reject(err)
						}
					}) */
				})
			},

			drawCard() {
				const padding = 15
				const cardWidth = this.width - (padding * 2)
				const cardHeight = this.height
				const cardX = padding
				const cardY = 30
				const radius = 12

				this.ctx.save()
				this.ctx.beginPath()
				this.ctx.arc(cardX + radius, cardY + radius, radius, Math.PI, Math.PI * 1.5)
				this.ctx.arc(cardX + cardWidth - radius, cardY + radius, radius, Math.PI * 1.5, Math.PI * 2)
				this.ctx.arc(cardX + cardWidth - radius, cardY + cardHeight - radius, radius, 0, Math.PI * 0.5)
				this.ctx.arc(cardX + radius, cardY + cardHeight - radius, radius, Math.PI * 0.5, Math.PI)
				this.ctx.closePath()

				this.ctx.setFillStyle('#ffffff')
				this.ctx.fill()
				this.ctx.restore()
			},

			drawNickname() {
				const x = 35
				const y = 90
				this.ctx.setFontSize(18)
				this.ctx.setFillStyle('#333333')
				this.ctx.fillText(this.nickname, x, y)
			},

			drawValues() {
				const startY = 120
				let currentY = startY
				Object.entries(this.values).forEach(([key, value]) => {
					this.ctx.setFontSize(14)
					this.ctx.setFillStyle('#A4A7AE')
					this.ctx.fillText(`${key}: ${value}`, 35, currentY)
					currentY += 25
				})
			},

			drawTips() {
				if (this.tip) {
					const tipsText = this.tip
					this.ctx.setFontSize(14)
					this.ctx.setFillStyle('#666666')
					const textWidth = this.ctx.measureText(tipsText).width
					const x = (this.width - textWidth) / 2
					this.ctx.fillText(tipsText, x, 350)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.share-card {
		position: relative;

		.share-canvas {
			position: relative;
		}
	}
</style>